<?php
/**
 * FastApp.
 * 10/26/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Service\Pay\Platform;

class XwinpayRSAUtils
{

    /**
     * 获取私钥
     *
     * @param string $privateKey 密钥字符串（经过base64编码）
     * @return resource 私钥资源
     */
    public static function getPrivateKey($privateKey)
    {
        $privateKey = "-----BEGIN PRIVATE KEY-----\n" . chunk_split($privateKey, 64, "\n") . "-----END PRIVATE KEY-----";
        return openssl_pkey_get_private($privateKey);
    }

    /**
     * 获取公钥
     *
     * @param string $publicKey 密钥字符串（经过base64编码）
     * @return resource 公钥资源
     */
    public static function getPublicKey($publicKey)
    {
        $publicKey = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($publicKey, 64, "\n") . "-----END PUBLIC KEY-----";
        return openssl_pkey_get_public($publicKey);
    }

    /**
     * RSA算法私钥加密数据
     *
     * @param string $data 待加密的明文字符串
     * @param string $privateKey RSA私钥字符串
     * @return string RSA私钥加密后的经过Base64编码的密文字符串
     */
    public static function encryptByPrivateKey(string $data, string $privateKey): string
    {
        $pi_key = self::getPrivateKey($privateKey);
        openssl_private_encrypt($data, $encrypted, $pi_key);
        return base64_encode($encrypted);
    }

    /**
     * RSA算法公钥解密数据
     *
     * @param string $data 待解密的经过Base64编码的密文字符串
     * @param string $publicKey RSA公钥字符串
     * @return string RSA公钥解密后的明文字符串
     */
    public static function decryptByPublicKey(string $data, string $publicKey): string
    {
        $pu_key = self::getPublicKey($publicKey);
        openssl_public_decrypt(base64_decode($data), $decrypted, $pu_key);
        return $decrypted;
    }
}